/**
 * http://www.koorz.com
 * Copyright (c) 2012 shanghai meiku information technology co,.ltd
 */
package com.koorz.oauth.services;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;
import com.koorz.constant.GlobalConstant;
import com.koorz.modules.user.PartyAccount;
import com.koorz.modules.user.User;
import com.koorz.oauth.model.OAuthConstants;
import com.koorz.oauth.model.OAuthRequest;
import com.koorz.oauth.model.Response;
import com.koorz.oauth.model.Token;
import com.koorz.oauth.model.UserWrapper;
import com.koorz.oauth.model.Verb;
import com.koorz.oauth.model.douban.DoubanToken;
import com.koorz.utils.FileUtil;
import com.koorz.utils.IdManage;
import com.koorz.utils.LoginUtil.WeiboType;
import com.koorz.utils.SystemConfig;

/**
 * 功能描述：
 * 作        者：尹东东 
 * 创建时间：2013-3-27 下午10:12:55
 * 版  本  号：1.0
 */
public class DoubanService extends ApiService{
	private String API_URL_PREFIX = "https://api.douban.com";
	private String USER_PREFIX = API_URL_PREFIX + "/v2/user";
	private String SHUO_PREFIX = API_URL_PREFIX + "/shuo/v2";
	
	public UserWrapper getUserInfo(String accessToken) {
		OAuthRequest request = createRequest(Verb.GET, USER_PREFIX+"/~me");
		request.addHeader(OAuthConstants.HEADER, "Bearer " + accessToken);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONObject json = JSON.parseObject(response.getBody());
	    	return wapperUser(json);
	    }
	    return null;
	}

	public Page<UserWrapper> getUserFollowers(String uid,int page,int count) {
		OAuthRequest request = createRequest(Verb.GET, String.format(SHUO_PREFIX+"/users/%s/followers",uid));
		request.addQuerystringParameter("start", (page-1)*count+"");
		request.addQuerystringParameter("count", count +"");
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	JSONArray usersJson = JSON.parseArray(response.getBody());
	    	if(usersJson.size() > 0){
	    		return new Page<UserWrapper>(wapperUsers(usersJson),page,count,page,count);
	    	}
	    }
	    return new Page<UserWrapper>(new ArrayList<UserWrapper>(0),page,count,0,0);
	}

	public int inviteFriend(String accessToken,String status,String atUser) {
		String inviteFriendTemplate = "我正在用%s。%s  @%s ";
		OAuthRequest request = createRequest(Verb.POST, SHUO_PREFIX+"/statuses/");
		request.addHeader(OAuthConstants.HEADER, "Bearer " + accessToken);
		request.addBodyParameter("source", SystemConfig.getValue("douban_client_ID"));
		request.addBodyParameter("text",String.format(inviteFriendTemplate,GlobalConstant.DOMAIN_HOST,status,atUser));
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	public int shareStatus(String accessToken,String status) {
		//String shareTemplate = "分享  %s 的歌曲 ♫%s:%s %s （分享自 @米蕊网）";
		OAuthRequest request = createRequest(Verb.POST, SHUO_PREFIX+"/statuses/");
		request.addHeader(OAuthConstants.HEADER, "Bearer " + accessToken);
		request.addBodyParameter("source", SystemConfig.getValue("douban_client_ID"));
		request.addBodyParameter("text", status);
	    Response response = request.send();
	    if(response.isSuccessful()){
	    	return 1;
	    }
	    return 0;
	}
	
	@Override
	protected UserWrapper wapperUser(JSONObject obj) {
		UserWrapper user = new UserWrapper();
		if(obj.containsKey("avatar")){
			user.setAvatar(obj.getString("avatar"));
		}
		if(obj.containsKey("small_avatar")){
			user.setAvatar(obj.getString("small_avatar"));
		}
		if(obj.containsKey("large_avatar")){
			user.setAvatarLarge(obj.getString("large_avatar"));
		}
		if(obj.containsKey("desc")){
			user.setDesc(obj.getString("desc"));
		}
		if(obj.containsKey("loc_name")){
			user.setLoc(obj.getString("loc_name"));
		}
		if(obj.containsKey("name")){
			user.setNickname(obj.getString("name"));
		}
		if(obj.containsKey("id")){
			user.setUid(obj.getString("id"));
		}
		if(obj.containsKey("screen_name")){
			user.setNickname(obj.getString("screen_name"));
		}
    	user.setGender(-1);
		return user;
	}

	@Override
	protected List<UserWrapper> wapperUsers(JSONArray array) {
		List<UserWrapper> users = new ArrayList<UserWrapper>();
		 for(int i=0;i<array.size();i++){
			 JSONObject userObj = array.getJSONObject(i);
			 users.add(wapperUser(userObj));
		 }
		 return users;
	}

	@Override
	public User bindUser(Token objClass) {
		DoubanToken accessToken = (DoubanToken) objClass;
		UserWrapper userWrapper = getUserInfo(accessToken.getAccessToken());
		User user = User.dao.findFirst("select u.id from user as u inner join party_account as pa on pa.user_id=u.id where pa.account_id=?",userWrapper.getUid());	
		if (user == null) {
			user = new User();
			String userId = IdManage.nextId(IdManage.USER);
			user.set("id", userId);
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.set("created_time", new Timestamp(Calendar.getInstance().getTimeInMillis()));
			user.set("score", 0);
			user.set("used_disk", 0);
			user.set("ranking", 0);
			user.set("upload_imitative_num", 0);
			user.set("upload_original_num", 0);
			user.set("upload_other_num", 0);
			user.set("artist_rate", 0.0);
			user.set("agents_rate", 0.0);
			user.set("singer_name", userWrapper.getNickname());
			user.set("region", userWrapper.getLoc());
			user.set("description", userWrapper.getDesc());
			user.set("user_website",GlobalConstant.DOMAIN_HOST + "/" + userId);
			user.set("tel", "");
			user.set("email", "");
			user.set("grade_id", "000000");
			//user.set("user_type",UserType.SELF.ordinal());
			user.save();
			
			PartyAccount account = new PartyAccount();
			account.set("id", IdManage.nextId(IdManage.PARTYACCOUNT));
			account.set("user_id", userId);
			account.set("account_id", userWrapper.getUid());
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.set("type", WeiboType.DOUBAN.ordinal());
			account.save();
//			for(int i=0;i<GlobalConstant.DEFAULTIMGS.length;i++){
//				ArtistsCover cover = new ArtistsCover();
//				cover.set("id", IdManage.nextId(IdManage.COVER));
//				cover.set("user_id", user.getStr("id"));
//				cover.set("img_url", GlobalConstant.DEFAULTIMGS[i]);
//				cover.set("is_show", 1);
//				cover.set("time", DateUtil.getNowDateTime());
//				cover.set("type", 0);
//				cover.save();
//			}
			
//			Db.update("insert into user_weibo_setting values(?,?,?,?,?,?)", 
//					IdManage.nextId(IdManage.USER_WEIBO_SETTING),
//					userId,WeiboType.DOUBAN.ordinal(),1,1,1);
			user.put("grade_name", "流浪歌手");
			user.put("grade_level", "Lv1");
			user.put("platform",WeiboType.DOUBAN.ordinal());
		} else {
			user.set("nickname",userWrapper.getNickname());
			user.set("gender", userWrapper.getGender());
			user.set("signature", userWrapper.getDesc());
			user.set("region", userWrapper.getLoc());
			user.set("description",userWrapper.getDesc());
			String tmp = FileUtil.saveAvatar(userWrapper.getAvatarLarge(), user.getStr("id"));
			if(StringUtils.isEmpty(tmp)){
				user.set("avatar", GlobalConstant.DEFAULT_AVATAR);
				user.set("avatar_large", GlobalConstant.DEFAULT_AVATAR_LARGE);
			}else {
				JSONObject avatarJson = JSON.parseObject(tmp);
				user.set("avatar", avatarJson.getString("avatar"));
				user.set("avatar_large", avatarJson.getString("avatarLarge"));
			}
			user.update();
			
			PartyAccount account = PartyAccount.dao.findFirst("select id,user_id,access_token,expires_in from party_account where user_id=? and account_id=?", 
					new Object[]{user.getStr("id"),userWrapper.getUid()});
			account.set("access_token", accessToken.getAccessToken());
			account.set("refresh_token", accessToken.getRefreshToken());
			account.set("expires_in", accessToken.getExpiresIn());
			account.update();
			
			user = User.dao.findFirst("select u.id,u.avatar,u.avatar_large,u.nickname,u.midou,u.user_website,u.score,u.ranking,g.name as grade_name,g.level as grade_level from user as u " +
						" inner join grade as g on g.id=u.grade_id " +
						" where u.id=?",user.getStr("id"));
			user.put("platform",WeiboType.DOUBAN.ordinal());
		}
		return user;
	}
	
	public static void main(String[] args) {
		DoubanService s = new DoubanService();
		String accessToken = "4dfd5d96d32f98c7e9f818c4798eca55";
		String uid = "114770";
		String appkey = "047d207d951594690d776178bf40bd3b";
//		Page<UserWrapper> wrapper = s.getUserFollowers(uid,1,10);
//		for(UserWrapper user:wrapper.getList()){
//			System.out.println(user.getNickname());
//		}
		//String accessToken,String status,String uid,String username,String songName
		s.shareStatus(accessToken,"spiral moon很好听 @noah0202 ");
	}
}
